import { defineStore } from "pinia"
import { reactive, watch } from "vue"
import { Exercise } from "../../model"
import { generateExercises as generate } from "./generate"
import { watchExerciseFinish } from "./handler"

export const useExerciseStore = defineStore("exercise", () => {
    const exercises: Exercise[] = reactive([])
    const unfinishedExercises: Exercise[] = reactive([])
    const finishedExercises: Exercise[] = reactive([])

    function addExercise(exercise: Exercise) {
        exercise = reactive(exercise)
        exercises.push(exercise)
        if (exercise.result == undefined) {
            unfinishedExercises.push(exercise)
            watchExerciseFinish(exercise)
            const stop = watch(
                () => exercise.result,
                (r) => {
                    if (r != undefined) {
                        stop()
                        const i = unfinishedExercises.indexOf(exercise)
                        if (i >= 0) unfinishedExercises.splice(i, 1)
                        finishedExercises.push(exercise)
                    }
                }
            )
        } else {
            finishedExercises.push(exercise)
        }
    }

    function generateExercises() {
        const generatedExercises = generate()
        generatedExercises.forEach(addExercise)
    }

    return {
        exercises,
        unfinishedExercises,
        finishedExercises,
        generateExercises,
    }
})
